package com.example.tool.activtiy;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.tool.R;
import com.example.tool.activtiy.base.BaseActivity;
import com.example.tool.mvp.CommonPresent;
import com.example.tool.okhttp.LoginMessage;
import com.example.tool.okhttp.basebean.ParamsBuilder;
import com.example.tool.okhttp.model.ModelSuperImpl;
import com.example.tool.okhttp.okhttps.EasyOk;
import com.example.tool.okhttp.okhttps.okcallback.OnDownloadListener;
import com.example.tool.okhttp.utils.OpenFileUtils;
import com.example.tool.okhttp.utils.ToastUtils;
import com.example.tool.util.DebugLog;
import com.example.tool.util.SpUtil;
import com.example.tool.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

import static com.example.tool.util.DebugLog.BREAK_DOWNLOAD;

/**
 * @description:网络上传下载工具
 * @author: liangkun
 * @date :   2020/5/26 11:26
 */
public class NetActivity extends BaseActivity<CommonPresent> implements OnDownloadListener {

    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okDown/demo/";
    private String fileName = "easyOk.apk";

    private String[] downloadUrl = {
            "http://update.9158.com/miaolive/Miaolive.apk",//喵播
            "https://apk-ssl.tancdn.com/3.5.3_276/%E6%8E%A2%E6%8E%A2.apk",//探探
            "https://o8g2z2sa4.qnssl.com/android/momo_8.18.5_c1.apk",//陌陌
            "http://s9.pstatp.com/package/apk/aweme/app_aweGW_v6.6.0_2905d5c.apk"//抖音
    };

    private static final String TAG = "MainActivity ";
    @BindView(R.id.txt_resumdown)
    TextView txt_resumdown;//断点下载
    @BindView(R.id.txt_cancledown)
    TextView txt_cancledown;//暂停下载
    @BindView(R.id.txt_delete)
    TextView txt_delete;
    @BindView(R.id.txt_total)
    TextView txt_total;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.txt_current)
    TextView txt_current;
    @BindView(R.id.txt_file)
    TextView txt_file;
    @BindView(R.id.txt_findfile)
    TextView txt_findfile;
    private boolean isExit;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_net;
    }

    @Override
    protected void initView() {
        txt_cancledown.setEnabled(false);
        File file = new File(path, fileName);
        if (file.exists()) {
            long currentfile = file.length();
            long total = (long) SpUtil.getLong("totalApk", currentfile);
            int present = (int) (currentfile * 100 / total);
            progressBar.setProgress(present);
            txt_current.setText(present + "%");
            txt_total.setText(round((double) total / 1024 / 1024, 2) + "M");
            txt_file.setText("文件路径 ==> " + file.getAbsolutePath() + "\n" + "文件目前大小 ==> " + round((double) file.length() / 1024 / 1024, 2) + "M)");
        } else {
            txt_file.setText("文件不存在");
        }
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initEvent() {

    }


    @OnClick({R.id.txt_down, R.id.txt_resumdown, R.id.txt_cancledown, R.id.txt_findfile, R.id.txt_delete})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_down:
                ModelSuperImpl.netWork().downApk(ParamsBuilder.build().path(path)
                        .fileName(fileName).tag("downApk"), this);
                setCancle(true);
                break;
            case R.id.txt_resumdown:
                ModelSuperImpl.netWork().downApk(ParamsBuilder.build().path(path)
                        .fileName(fileName).tag("downApk").resume(true), this);
                setCancle(true);
                break;
            case R.id.txt_cancledown:
                EasyOk.getInstance().cancleOkhttpTag("downApk");
                setCancle(false);
                break;

            case R.id.txt_findfile:
                openAndroidFile(new File(path, fileName));
                break;
            case R.id.txt_delete:
                File file = new File(path, fileName);
                if (file.exists()) {
                    if (file.delete()) {
                        ToastUtil.toastShortContent("删除成功");
                        progressBar.setProgress(0);
                        txt_current.setText("0%");
                        txt_file.setText("文件不存在");
                    }
                }
                break;
        }
    }

    //这是打开文件的方式，并不是正确的安装apk。。
    public void openAndroidFile(File file) {
        if (!file.exists()) {
            ToastUtils.showToast("文件不存在");
            return;
        }
        Intent intent = new Intent();
        // 这是比较流氓的方法，绕过7.0的文件权限检查
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置标记
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setAction(Intent.ACTION_VIEW);//动作，查看ACTION_VIEW
        intent.setDataAndType(Uri.fromFile(file), OpenFileUtils.getMIMEType(file));//设置类型OpenFileUtils.getMIMEType(file)
        startActivity(intent);
    }

    @Override
    protected CommonPresent createPresenter() {
        return null;
    }


    //保留几位小数
    public double round(Double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = null == v ? new BigDecimal("0.0") : new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Override
    public void onDownloadSuccess(File file) {
        if (!isExit) {

            ToastUtils.showToast("下载成功");
        }
        setCancle(false);
    }

    @Override
    public void onDownLoadTotal(long total) {
        if (!isExit) {
            txt_total.setText(round((double) total / 1024 / 1024, 2) + "M");
        }
        SpUtil.putLong("totalApk", total);

    }

    @Override
    public void onDownloading(int progress) {
        if (!isExit) {
            progressBar.setProgress(progress);
            txt_current.setText(progress + "%");
//            txt_content.setText("当前下载进度 ==> " + progress);
            File file = new File(path, fileName);
            txt_file.setText("文件路径 ==> " + file.getAbsolutePath() + "\n" + "目前文件大小 ==> " + round((double) file.length() / 1024 / 1024, 2) + "M");
        }


    }

    @Override
    public void onDownloadFailed(Exception e) {
        if (!isExit) {

            ToastUtils.showToast("下载失败 == >" + e.toString());
        }
    }


    public void setCancle(boolean cancle) {
        if (!isExit) {
            txt_resumdown.setEnabled(!cancle);
            txt_findfile.setEnabled(!cancle);
            txt_delete.setEnabled(!cancle);
            txt_cancledown.setEnabled(cancle);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onbackEvent(LoginMessage message) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        isExit = true;
        //退出一个页面。取消这个页面所有正在进行的网络请求
        DebugLog.d(BREAK_DOWNLOAD + "onStop----------");
        EasyOk.getInstance().cancleOkhttpTag(this.getClass().toString());
        EventBus.getDefault().unregister(this);
    }
}
